package com.ruoyi.miniapp.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.miniapp.config.CashInfoProperty;
import com.ruoyi.miniapp.service.IAccountInfoService;
import com.ruoyi.miniapp.service.IBankInfoService;
import com.ruoyi.miniapp.service.IInvoiceInfoService;
import com.ruoyi.miniapp.service.IWithdrawalsRecordService;
import com.ruoyi.system.api.domain.base.AccountInfo;
import com.ruoyi.system.api.domain.base.BankInfo;
import com.ruoyi.system.api.domain.base.WithdrawalsRecord;
import com.tdd.wx.users.api.WxUserServiceApi;
import com.tdd.wx.users.entity.WxUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Wrapper;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("withdrawalsRecord")
@Api(tags = "提现记录")
public class WithdrawalsRecordController {

    @Autowired
    private IWithdrawalsRecordService iWithdrawalsRecordService;
    @Autowired
    private IAccountInfoService iAccountInfoService;
    @Autowired
    private IInvoiceInfoService iInvoiceInfoService;
    @Autowired
    private IBankInfoService iBankInfoService;
    @Autowired
    private CashInfoProperty cashInfoProperty;

    @DubboReference(version = "3.0.0" , interfaceClass = WxUserServiceApi.class, interfaceName = "WxUserService" , lazy = true, check = false)
    private WxUserServiceApi wxUserServiceApi;

    @ApiOperation("查看余额")
    @GetMapping("getBalance")
    public R<AccountInfo> getBalance(String unionid){
        if(StrUtil.isEmpty(unionid)){
            unionid = SecurityUtils.getUnionId();
        }
        WxUser wxUser = wxUserServiceApi.findByUnionId(unionid);
        if(wxUser == null || wxUser.getSysUserId() == null){
            return R.fail("请先登录！");
        }
        AccountInfo accountInfo = iAccountInfoService.getById(wxUser.getSysUserId());
        if(accountInfo == null){
            accountInfo = iAccountInfoService.initAccountInfo(wxUser.getSysUserId(),wxUser.getUnionId(),wxUser.getOpenId(),BigDecimal.ZERO);
        }
        accountInfo.setTaxRate(cashInfoProperty.getTaxRate());
        return R.ok(accountInfo);
    }


    @ApiOperation("申请提现")
    @PostMapping("applyCash")
    public R applyCash(@RequestBody WithdrawalsRecord withdrawalsRecord){
        String unionid = withdrawalsRecord.getUnionid();
        if(StrUtil.isEmpty(unionid)){
            unionid = SecurityUtils.getUnionId();
        }
        WxUser wxUser = wxUserServiceApi.findByUnionId(unionid);
        if(wxUser == null || wxUser.getSysUserId() == null){
            return R.fail("请先登录！");
        }
        if(withdrawalsRecord.getMoney().compareTo(new BigDecimal(800)) < 0){
            return R.fail("提现金额不满足！");
        }

        AccountInfo accountInfo = iAccountInfoService.getById(wxUser.getSysUserId());
        if(accountInfo == null){
            iAccountInfoService.initAccountInfo(wxUser.getSysUserId(),wxUser.getUnionId(),wxUser.getOpenId(),BigDecimal.ZERO);
        }
        Map map = iAccountInfoService.updateBalance(wxUser.getSysUserId(),withdrawalsRecord.getMoney(),false,"apply_cash","申请提现");
        if(!MapUtil.getBool(map,"flag",false)){
            return R.fail(MapUtil.getStr(map,"msg","扣款失败！"));
        }
        BigDecimal newBalance = new BigDecimal(MapUtil.getStr(map,"balance","0"));
        withdrawalsRecord.setUserId(wxUser.getSysUserId());
        withdrawalsRecord.setLaterMoney(newBalance);
        withdrawalsRecord.setWithdrawOrigin(1);
        withdrawalsRecord.setWithdrawalsState(10);
        withdrawalsRecord.setWithdrawalsTime(DateTime.now());
        if(StrUtil.isEmpty(withdrawalsRecord.getResId()) && StrUtil.isEmpty(withdrawalsRecord.getElecInvoiceUrl())){
            //计算税费
            BigDecimal taxAmount = withdrawalsRecord.getMoney().multiply(cashInfoProperty.getTaxRate());
            BigDecimal actualAcount = withdrawalsRecord.getMoney().subtract(taxAmount);

            withdrawalsRecord.setActualAccountAmount(actualAcount);
            withdrawalsRecord.setTaxAmount(taxAmount);
            withdrawalsRecord.setTaxRate(cashInfoProperty.getTaxRate());
        }
        iWithdrawalsRecordService.save(withdrawalsRecord);
        return R.ok();
    }

    @ApiOperation("银行列表")
    @GetMapping("bankList")
    public R<List<BankInfo>> bankList(){
        return R.ok(iBankInfoService.list());
    }


    @ApiOperation("查看自己提现记录")
    @GetMapping("selfListPage")
    public R<Page<WithdrawalsRecord>> selfListPage(Page<WithdrawalsRecord> page,String unionid){
        if(StrUtil.isEmpty(unionid)){
            unionid = SecurityUtils.getUnionId();
        }
        WxUser wxUser = wxUserServiceApi.findByUnionId(unionid);
        if(wxUser == null || wxUser.getSysUserId() == null){
            return R.fail("请先登录！");
        }
        return R.ok(iWithdrawalsRecordService.listPage(page,wxUser.getSysUserId()));
    }
}
